extends ../layout/_layout

append pageCss
    link(rel="stylesheet", href=`${setting.static}static/css/post.css?t=${setting.tstamp}`)

append content

    include ../layout/header-small

    main.page__container.page__main
        .page__content
            .content__container
                #form-list
                    .form-label
                        .label-desc 文章 id
                        .label-content
                            input#postid.label-input(type="text", data-post="path")

                    .form-label
                        .label-desc 标题
                        .label-content
                            input.label-input(type="text", data-post="title")

                    .form-label
                        .label-desc 副标题
                        .label-content
                            input.label-input(type="text", data-post="subtitle")

                    .form-label
                        .label-desc 作者
                        .label-content
                            input.label-input(type="text", value="keydone", data-post="author")

                    .form-label
                        .label-desc 文章分类
                        .label-content
                            input.label-input(type="text", data-post="category")

                    .form-label
                        .label-desc 文章标签
                        .label-content
                            input.label-input(type="text", placeholder="多个标签之间用 , 分开" data-post="tags")

                    .form-label
                        .label-desc 发布时间
                        .label-content
                            input#postdate.label-input(type="text", data-post="date")

                        .label-desc 封面图片地址
                        .label-content.cover-update
                            input#postcover.label-input(type="text", data-post="cover")
                    //- 上传封面
                    .form-label
                        .label-desc 上传封面图
                        .label-content
                             input#file-cover.filepond(type="file")

                a#closeForm.closeForm.open(href="javascript:;")
                    i.icon.icon-top

                .post-content
                    .form-label
                        .label-desc 内容
                        .label-content
                            textarea#textarea.label-textarea(type="text", rows="50", data-post="content")

                        .post-btns
                            a#draft(href="javascript:;") 存为草稿
                            a#update(href="javascript:;") 更新
                            a#post(href="javascript:;") 发布

                    .form-label.preview-view
                        .label-desc 预览
                        #preview

append pagejs
    script(type="text/javascript", src=`${setting.static}static/js/filepond.min.js?t=${setting.tstamp}`)
    script(src=`${setting.static}static/js/markdown-it.min.js?t=${setting.tstamp}`)
    script(src=`${setting.static}static/js/md-plugins.js?t=${setting.tstamp}`)
    script.
        window.addEventListener('DOMContentLoaded', function() {
            var postid = $('#postid');
            FilePond.create(document.querySelector('#file-cover'), {
                labelIdle: '拖拽或 <span class="filepond--label-action"> 浏览文件 </span>',
                labelFileWaitingForSize: '正在加载文件信息',
                labelFileSizeNotAvailable: '大小不可用',
                labelFileLoading: '正在加载',
                labelFileLoadError: '加载文件失败',
                labelFileProcessing: '正在上传',
                labelFileProcessingComplete: '已完成',
                labelFileProcessingAborted: '已取消',
                labelFileProcessingError: '上传失败',
                labelTapToCancel: '取消',
                labelTapToRetry: '重试',
                labelTapToUndo: '撤销',
                labelButtonRemoveItem: '移除',
                labelButtonAbortItemLoad: '中断',
                labelButtonRetryItemLoad: '重试',
                labelButtonAbortItemProcessing: '中断',
                labelButtonUndoItemProcessing: '撤销',
                labelButtonRetryItemProcessing: '重试',
                labelButtonProcessItem: '上传',
                name: 'filepond',
                allowRevert: true,
                allowMultiple:true,
                dropOnPage: true,
                dropValidation: true,
                onerror: function(error, file, status) {
                    console.log(error, file, status);
                }
            });

            function setOptions() {
                FilePond.setOptions({
                    server: {
                        url: '/api/img-upload?store=img&postid=' + postid.val(),
                        process: {
                            onload: function(res) {
                                var res = JSON.parse(res);
                                if(+res.status === 0) {
                                    $('#postcover').val(res.data.path);
                                    // FilePond.removeFile();
                                }
                            }
                        }
                    },
                });
            }

            setOptions();

            postid.on('blur', function() {
                setOptions();
            });
        }, false);
    script.
        var textarea = $('#textarea');
        var preview = $('#preview');
        var md = window.markdownit({
            html: true,
            breaks: true,
            linkify: true,
            xhtmlOut: true,
            typographer: true,
            highlight: function (str, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    try {
                        return '<pre class="hljs"><code>' + hljs.highlight(lang, str, true).value + '</code></pre>';
                    } catch (__) { }
                }
                return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
            }
        }).use(window.markdownitEmoji)
        .use(window.markdownitCheckbox, {
            divWrap: true,
            divClass: 'checkbox',
            idPrefix: 'checkbox_'
        })
        .use(window.markdownitLinkScheme)
        .use(window.markdownitDeflist)
        .use(window.markdownitDiv);
        // 实时更新预览
        textarea.on('input', function() {
            var result = md.render(textarea.val());
            preview.html(result);
            scrollMap = null;
        });
        // 内容与预览区域同步滚动
        function injectLineNumbers(tokens, idx, options, env, slf) {
            var line;
            if (tokens[idx].map && tokens[idx].level === 0) {
                line = tokens[idx].map[0];
                tokens[idx].attrJoin('class', 'line');
                tokens[idx].attrSet('data-line', String(line));
            }
            return slf.renderToken(tokens, idx, options, env, slf);
        }

        md.renderer.rules.paragraph_open = md.renderer.rules.heading_open = injectLineNumbers;

        var scrollMap;
        function buildScrollMap() {
            var i, offset, nonEmptyList, pos, a, b, lineHeightMap, linesCount, acc, sourceLikeDiv, _scrollMap;

            sourceLikeDiv = $('<div />').css({
                position: 'absolute',
                visibility: 'hidden',
                width: textarea[0].clientWidth,
                'font-size': textarea.css('font-size'),
                'font-family': textarea.css('font-family'),
                'line-height': textarea.css('line-height'),
                'white-space': textarea.css('white-space')
            }).appendTo('body');

            offset = preview.scrollTop() - preview.offset().top;
            _scrollMap = [];
            nonEmptyList = [];
            lineHeightMap = [];

            acc = 0;
            textarea.val().split('\n').forEach(function (str) {
                var h, lh;

                lineHeightMap.push(acc);

                if (str.length === 0) {
                    acc++;
                    return;
                }

                sourceLikeDiv.text(str);
                h = parseFloat(sourceLikeDiv.css('height'));
                lh = parseFloat(sourceLikeDiv.css('line-height'));
                acc += Math.round(h / lh);
            });
            sourceLikeDiv.remove();
            lineHeightMap.push(acc);
            linesCount = acc;

            for (i = 0; i < linesCount; i++) { _scrollMap.push(-1); }

            nonEmptyList.push(0);
            _scrollMap[0] = 0;

            $('.line').each(function (n, el) {
                var $el = $(el), t = $el.data('line');
                if (t === '') { return; }
                t = lineHeightMap[t];
                if (t !== 0) { nonEmptyList.push(t); }
                _scrollMap[t] = Math.round($el.offset().top + offset);
            });

            nonEmptyList.push(linesCount);
            _scrollMap[linesCount] = preview[0].scrollHeight;

            pos = 0;
            for (i = 1; i < linesCount; i++) {
                if (_scrollMap[i] !== -1) {
                pos++;
                continue;
                }

                a = nonEmptyList[pos];
                b = nonEmptyList[pos + 1];
                _scrollMap[i] = Math.round((_scrollMap[b] * (i - a) + _scrollMap[a] * (b - i)) / (b - a));
            }

            return _scrollMap;
        }
        // Synchronize scroll position from source to result
        var syncResultScroll = _.debounce(function () {
            var lineHeight = parseFloat(textarea.css('line-height')), lineNo, posTo;

            lineNo = Math.floor(textarea.scrollTop() / lineHeight);
            if (!scrollMap) {
                scrollMap = buildScrollMap();
            }
            posTo = scrollMap[lineNo];

            preview.stop(true).animate({
                scrollTop: posTo
            }, 50, 'linear');
        }, 50, { maxWait: 33 });

        var syncSrcScroll = _.debounce(function () {
            var scrollTop  = preview.scrollTop(),
                lineHeight = parseFloat(textarea.css('line-height')), lines, i, line;

            if (!scrollMap) {
                scrollMap = buildScrollMap();
            }

            lines = Object.keys(scrollMap);

            if (lines.length < 1) {
                return;
            }

            line = lines[0];

            for (i = 1; i < lines.length; i++) {
                if (scrollMap[lines[i]] < scrollTop) {
                    line = lines[i];
                    continue;
                }
                break;
            }

            textarea.animate({
                scrollTop: lineHeight * line
            }, 50, 'linear');
        }, 50, { maxWait: 33 });

        // Setup listeners
        textarea.on('touchstart mouseover', function () {
            preview.off('scroll');
            textarea.on('scroll', syncResultScroll);
        });

        preview.on('touchstart mouseover', function () {
            textarea.off('scroll');
            preview.on('scroll', syncSrcScroll);
        });

    script.
        var closeForm = $('#closeForm'),
            formlist = $('#form-list'),
            post = $('#post'),
            draft = $('#draft'),
            fields = $('[data-post]'),
            data = {};

        function today() {
            var now = new Date();
            var year = now.getFullYear();
            var month = now.getMonth() + 1;
            if (month < 10) {
                month = String(month).padStart(2, '0');
            }
            var date = now.getDate();
            if (date < 10) {
                date = String(date).padStart(2, '0');
            }

            return year + '-' + month + '-' + date;
        };

        $('#postdate').val(today());

        function publish(type) {

            for(var i=0, length=fields.length; i<length; i++) {
                const item = $(fields[i]);
                var key = item.attr('data-post');
                var val = item.val();
                data[key] = val;
            }

            data.isDraft = type;

            $.ajax({
                type: 'POST',
                url: '/admin/post-save',
                dataType: 'json',
                data: data,
                success: function(res) {
                    if(res.status === 0) {
                        console.log('success');
                    }
                },
            });
        }

        post.on('click', function() {
            publish(0);
        });

        draft.on('click', function() {
            publish(1);
        });

        closeForm.on('click', function() {
            $(this).toggleClass('open');
            formlist.toggleClass('closed');
        });
